package com.hnl.action.talent;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hnl.core.HNLPageDispatch;
import com.hnl.core.aware.HNLAuthAware;
import com.hnl.core.aware.HNLTalentAware;
import com.hnl.core.aware.MiscTypeAware;
import com.hnl.dao.DAOException;
import com.hnl.dao.EducationDAO;
import com.hnl.dao.HNLDAOFactory;
import com.hnl.to.Education;
import com.hnl.util.JSONResponseUtil;

@SuppressWarnings("serial")
public class AddEducation extends HttpServlet implements HNLAuthAware,
		HNLTalentAware, MiscTypeAware, HNLPageDispatch {
	public static final Logger LOG = LoggerFactory
			.getLogger(AddEducation.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			PrintWriter writer = resp.getWriter();
		try {
			String talentID = req.getParameter(ATTRIBUTE_TALENT_ID);
			String state = req.getParameter(ATTRIBUTE_EDUCATION_EDIT_STATE);
			EducationDAO eduDAO = HNLDAOFactory.getDAOFactory(
					HNLDAOFactory.HNLDAOFACTORY).getEducationDAO();
			Education newEdu = new Education();

			newEdu.setTalent_ID(Integer.parseInt(talentID));
			newEdu.setDegree(req.getParameter("degree"));
			newEdu.setDuration(req.getParameter("duration"));
			newEdu.setIsdelete(false);
			newEdu.setMajor(req.getParameter("major"));
			newEdu.setSchool(req.getParameter("school"));
			if (state.equals("new")) {
				eduDAO.saveEducation(newEdu);
			} else if (state.equals("modify")) {
				newEdu.setTalent_education_ID(Integer.valueOf(req
						.getParameter(ATTRIBUTE_EDUCATION_ID)));
				eduDAO.updateEducation(newEdu);
			}

			Collection<Education> eduCollection = eduDAO.loadEducation(Integer
					.valueOf(talentID));
			
			writer.println(JSONResponseUtil.getJSONObjectString(eduCollection));
		} catch (DAOException e) {
			LOG.error("Error to add talent.", e);
		} finally {
			writer.close();
		}

	}
}
